package com.tech.platform.cms.authz.common.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.*;

import java.util.Date;

public class JwtUtils {

    public static String generatorToken(String id,String subject,String secretKey){
        long now = System.currentTimeMillis();  //当前时间
        long exp = now + 1000 * 60 * 60 * 2; //过期时间为2小时
        return Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(new Date())
                .setExpiration(new Date(exp))
                .signWith(SignatureAlgorithm.HS256,secretKey).compact();
    }

    public static boolean checkToken(String token,String secretKey) throws JwtException {
        Jwts.parser().setSigningKey(secretKey).parse(token).getBody();
        return true;
    }

    public static Claims getClaims(String token,String secretKey) throws JwtException{
        if(StrUtil.isBlank(token)){
            throw new IllegalArgumentException("jwt token is not exist");
        }

        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
    }

    public static boolean isTokenExpired(String token,String secretKey) throws JwtException, ExpiredJwtException {
        Date expiredDate = getClaims(token,secretKey).getExpiration();
        return expiredDate.before(new Date());
    }
}
